name: Sync Release Manifest
on:
  repository_dispatch:
    types: [release-published]

jobs:
  create-new-version:
    runs-on: ubuntu-latest
    steps:
      - name: Harden Runner
        uses: step-security/harden-runner@63c24ba6bd7ba022e95695ff85de572c04a18142 # v2.7.0
        with:
          egress-policy: audit

      # Setup node & install deps before checkout, keeping install quick
      - uses: actions/setup-node@60edb5dd545a775178f52524783378180af0d1f8 # v4.0.2
        with:
          node-version: 18.x
      - name: Install dependencies
        # Just the deps for the assemble manifest script
        run: npm install semver@7.3.5 fs-extra@10.0.0 @manypkg/get-packages@1.1.1

      - name: Checkout
        uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
        with:
          path: backstage
          # 'v' prefix is added here for the tag, we keep it out of the manifest logic
          ref: v${{ github.event.client_payload.version }}

      # Checkout backstage/versions into /backstage/versions, which is where store the output
      - name: Checkout versions
        uses: actions/checkout@b4ffde65f46336ab88eb53be808477a3936bae11 # v4.1.1
        with:
          repository: backstage/versions
          path: backstage/versions
          token: ${{ secrets.GH_SERVICE_ACCOUNT_TOKEN }}

      - name: Configure Git
        run: |
          git config --global user.email noreply@backstage.io
          git config --global user.name 'Github versions workflow'

      - name: Create release
        # This grabs the scripts from master in order to support backfills
        run: |
          cd backstage
          mkdir -p scripts
          wget -O scripts/assemble-manifest.js https://raw.githubusercontent.com/backstage/backstage/master/scripts/assemble-manifest.js
          node scripts/assemble-manifest.js ${{ github.event.client_payload.version }}
          cd versions
          git add .
          git commit -am "${{ github.event.client_payload.version }}"
          git push

      - name: Dispatch update-helper update
        uses: actions/github-script@60a0d83039c74a4aee543508d2ffcb1c3799cdea # v7.0.1
        with:
          github-token: ${{ secrets.GH_SERVICE_ACCOUNT_TOKEN }}
          # TODO(Rugvip): Remove the create-app dispatch once we've been on the release version for a while
          script: |
            console.log('Dispatching upgrade helper sync');
            await github.rest.actions.createWorkflowDispatch({
              owner: 'backstage',
              repo: 'upgrade-helper-diff',
              workflow_id: 'release.yml',
              ref: 'master',
              inputs: {
                version: require('./backstage/packages/create-app/package.json').version,
                releaseVersion: require('./backstage/package.json').version
              },
            });
